

(function($) {
	// tracker varialbels
	$.kulstats.tracker = {};
	// collection of counter objects
	$.kulstats.counters = {};
	$.kulstats.tracker.progress = {};
})(jQuery);

$('#trackPage').live('pageinit',function(e) {
	
	//initializing tracker variables
	$.kulstats.tracker.server = $('#track_form').attr('action');
	$.kulstats.tracker.type = "study";
	$.kulstats.tracker.paused = 0;
	$.kulstats.tracker.progress.bar = $("#track_milestoneprogress");
	$.kulstats.tracker.progress.ini = 0;
	$.kulstats.tracker.progress.cur = 0;
	$.kulstats.tracker.progress.tot = 0;
	// initializing counter objects
	$.kulstats.counters.track = {running: false, start: $("#track_start"), display: $("#track_counter")};
	$.kulstats.counters.pause = {running: false, start: $("#track_pause_start"), display: $("#track_pauser")};

	/** 
	 * Trackable form elements:
	 * - track_course
	 * - track_location
	 * - track_spare_type
	 * 
	 * All trackable elements are included in div tags with 
	 * IDs div_ followed by form element id. f.e. div_track_course
	 */
	
	$('.track_type_select').change(function(e) {
		var type = $('[name=track_type_select]:checked').val();
		$("[id^=div_track_]").hide();
		$.kulstats.tracker.type = type;
		switch(type) {
			case 'study':
				$('#div_track_course').slideDown();
				$('#div_track_location').slideDown();
				break;
			case 'lesson':
			$('#div_track_course').slideDown();
			$('#div_track_lesson_type').slideDown();
				break;
			case 'spare_time':
				$('#div_track_spare_type').slideDown();
				break;
		}
	});
	
	//the start button
	$('#butt_track_start').click(function(e) {
		var startVal = new Date().getTime();
		//submitting current data
		$.post($.kulstats.tracker.server, {
			"action"            : "action_new",
			"track_type"        : $.kulstats.tracker.type,
			"track_start"       : startVal,
			"track_course"      : $("#track_course").val(),
			"track_lesson_type"  : $("[name=track_lesson_type]:checked").val(), //( $("#track_lesson_type_1").checked ? "lecture" : "practice" ),
			"track_location"    : $("#track_location").val(),
			"track_spare_type"  : $("#track_spare_type").val()
		}, function(resp) {
			resp = $.parseJSON(resp);
			$.resp = resp;
			if(resp.status == "success") {
				//check if all entered values are correct and possible..
				$('#content_init').hide();
				$('#content_busy').show();
				$('#track_start').val(startVal);
				$.kulstats.counters.track.running = true;
				doCount($.kulstats.counters.track);
				if($.kulstats.tracker.type == "study") {
					$('[id^=track_pause]').show();
				}
				if(($.kulstats.tracker.type == "study" || $.kulstats.tracker.type == "lesson") &&parseInt(resp.progress_tot) > 0) {
					$.kulstats.tracker.progress.ini = parseInt(resp.progress_now)/1000;
					$.kulstats.tracker.progress.cur = $.kulstats.tracker.progress.ini;
					$.kulstats.tracker.progress.tot = parseInt(resp.progress_tot)/1000;
					$.kulstats.tracker.progress.bar.show();
					createProgress($.kulstats.tracker.progress);
					setTimeout("doProgress();",1000);
				}
			}
			else {
				alert("Error 01: please try again");
			}
		});
	});
	
	//pausing:
	$('#button_pause_on').click(function(e) {
		if($.kulstats.counters.pause.running != true) {
			var startVal = new Date().getTime();
			//send pause to server and start counter if succesfull
			$.post($.kulstats.tracker.server, {
				"action"      : "action_start_pause",
				"pause_start" : startVal
			}, function(resp) {
				resp = $.parseJSON(resp);
				if(resp.status == "success") {
					$.kulstats.counters.pause.running = true;
					$.kulstats.counters.pause.start.val(startVal);
					doCount($.kulstats.counters.pause);
					$('#button_pause_on').hide();
					$('#button_pause_off').show();
				}
				else {
					alert("Error 02: please try again");
				}
			});
		}
	});
	$('#button_pause_off').click(function(e) {
		var stopVal = new Date().getTime();
		$.post($.kulstats.tracker.server, {
			"action"      : "action_stop_pause",
			"pause_stop"  : stopVal
		}, function(resp) {
			resp = $.parseJSON(resp);
			if(resp.status == "success") {
				$.kulstats.tracker.paused += stopVal - parseInt($.kulstats.counters.pause.start.val(0));
				$.kulstats.counters.pause.running = false;
				$.kulstats.counters.pause.start.val(0);
				$.kulstats.counters.pause.display.html("00:00:00");
				$('#button_pause_off').hide();
				$('#button_pause_on').show();
			}
		});
	});
	
	//the stop button
	$('#butt_track_stop').click(function(e) {
		$.post($.kulstats.tracker.server, {
			"action"  : "action_stop",
			"track_stop" : new Date().getTime()
		}, function(resp) {
			resp = $.parseJSON(resp);
			if(resp.status == "success") {
				//stop both counters
				$.kulstats.counters.track.running = false;
				$.kulstats.counters.pause.running = false;
				// show questionnaire
				//$('#content_finished_main').text(data);
				$('#content_busy').hide();
				$('#content_questions').slideDown();
				if(resp.questions) {
					showQuestions(resp.questions);
				}
			}
			else {
				alert("Failed: ");
			}
		});
	});

	//the submit questions button
	$('#button_questions_submit').click(function(e) {
		$.post($.kulstats.tracker.server, "action=action_save_questions&"+$("#questionForm").serialize(), function(resp) {
			resp = $.parseJSON(resp);
			if(resp.status == "success") {
				$('#content_questions').hide();
				$('#content_finished').show();
				document.location = "/track";
			}
			else {
				alert("Failed: ");
			}
		});
	});
	//the skip questions button
	$('#button_questions_skip').click(function(e) {
		/*$.post($.kulstats.tracker.server, {
			"action" : "action_skip_questions"
		}, function(resp) {
			resp = $.parseJSON(resp);
			if(resp.status == "success") {
				$('#content_questions').hide();
				$('#content_finished').show();
			}
			else {
				alert("Failed: ");
			}
		});*/
		$('#content_questions').hide();
		$('#content_finished').show();
		document.location = "/track";
	});

	//restore already running event:
	if($('#track_start').val() > 0 && $("#track_type") != "") {
		$.kulstats.tracker.type = $('#track_type').val();
		$.kulstats.counters.track.running = true;
		doCount($.kulstats.counters.track);
		if($.kulstats.tracker.type == "study") {
			$('[id^=track_pause]').show();
			if($.kulstats.counters.pause.start.val() > 0) {
				$.kulstats.counters.pause.running = true;
				doCount($.kulstats.counters.pause);
				$('#button_pause_on').hide();
				$('#button_pause_off').show();
			}
		}
		if($.kulstats.tracker.type == "study" || $.kulstats.tracker.type == "lesson") {
			if(parseInt($("#track_prog2").val()) > 0) {
				$.kulstats.tracker.progress.ini = parseInt($("#track_prog1").val())/1000;
				$.kulstats.tracker.progress.cur = $.kulstats.tracker.progress.ini;
				$.kulstats.tracker.progress.tot = parseInt($("#track_prog2").val())/1000;
				$.kulstats.tracker.progress.bar.show();
				createProgress($.kulstats.tracker.progress);
				setTimeout("doProgress();",20);
			}
		}
	}
});

//once tracking is done, question form needs to be shown
function showQuestions(questions) {
	// questions are recieved through ajax after stopping the tracker
	// and are iterated here to ask them all
	for(var i=0 ; questions[i] ; i++) {
		q = questions[i];
		// create a new fieldcontain div tag to show this question in
		// and put a label tag in it with the question text
		newDiv = $("<div/>")
			.attr("data-role","fieldcontain")
			.append(
				$("<label/>")
					.attr("for","track_question_"+i)
					.text(q.question)
			.append(
				$("<input/>")
					.attr("type","hidden")
					.attr("name","track_question_"+i+"_qid")
					.val(q.qid)
			)
		);
		// alist id a1 represents a 5 star rating question and is handled seperately
		// all other questions are handled the same way
		if(q.alistid == "a1") {
			newDiv.append(getStarRating("track_question_"+i));
		}
		else {
			// just create a selectbox with all the possible answers received from the server
			selectBox = $("<select/>")
				.attr("id","track_question_"+i)
				.attr("name","track_question_"+i);
			for(var j=0 ; q.alist[j] ; j++) {
				selectBox.append(
					$("<option/>")
						.val( q.alist[j])
						.text(q.alist[j])
				);
			}
			newDiv.append(selectBox);
		}
		$('#content_questions_questions').append(newDiv);
	}
}

function doCount(counter) {
	if(counter.running == true) {
		var timeDiff = parseInt(( new Date().getTime() - parseInt(counter.start.val()) ) / 1000);
		var secs = parseInt(timeDiff % 60);
		timeDiff = parseInt(timeDiff / 60);
		var mins = parseInt(timeDiff % 60);
		timeDiff = parseInt(timeDiff / 60);
		var hour = timeDiff;

		var timeString = '';
		if(hour < 10)
			timeString += '0';
		timeString += hour + ':';
		if(mins < 10)
			timeString += '0';
		timeString += mins + ':';
		if(secs < 10)
			timeString += '0';
		timeString += secs;
		counter.display.html(timeString);
	
		setTimeout(function(c){ doCount(c); },1000,counter);
	}
}

function doProgress() {
	if($.kulstats.counters.pause.running != true) {
		var curTime = parseInt($.kulstats.tracker.progress.ini);
		curTime += (new Date().getTime() - parseInt($.kulstats.counters.track.start.val()))/1000;
		curTime -= parseInt($.kulstats.tracker.paused)/1000;
		$.kulstats.tracker.progress.cur = parseInt(curTime);
		setProgress($.kulstats.tracker.progress);
	}
	setTimeout("doProgress()",3000);
}


//generate a star rating element
function getStarRating(name) {
	div = $("<div/>")
	.attr("id",name+"_div")
	.css("width", "231px")
	.css("height","46px");
	for(var i=1 ; i < 6 ; i++) {
		div.append(
				$("<img/>")
				.attr("id",name+"_"+i)
				.attr("src","images/star_white.png")
				.css("width", "46px")
				.css("height","46px")
				.attr("onclick","doStarRating('"+name+"',"+i+")")
		);
	}
	div.append(
			$("<input/>")
			.attr("type","hidden")
			.attr("name",name)
			.attr("id",name)
			.val(0)
	);
	return div;
}
function doStarRating(name,r) {
	r = parseInt(r);
	if($("#"+name).val() != r && r >= 1 && r <= 5) {
		$("#"+name).val(r);
		for(var i=0 ; i < 6 ; i++) {
			$('#'+name+'_'+i).attr("src",(i <= r ? "images/star_yellow.png" : "images/star_white.png"));
		}
	}
}

